package com.swak.fx.support.ui;

import java.io.InputStream;

import com.swak.exception.NoSupportException;

import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.FXCollections;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.VPos;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;

/**
 * 多图，最多显示9张图， 9宫格显示
 * 
 * @author 618lf
 */
public class UIImages extends GridPane implements UILifecycle {

	// ================================================================================
	// Properties
	// ================================================================================
	private final String STYLE_CLASS = "ui-images";
	private final ListProperty<Object> nodesProperty = new SimpleListProperty<Object>(
			FXCollections.observableArrayList());

	public UIImages() {
		this.init();
	}

	@Override
	public void initializeParts() {
		getStyleClass().add(STYLE_CLASS);
		this.setPadding(Insets.EMPTY);
		this.setGridLinesVisible(false);
		this.setHgap(0);
		this.setVgap(0);
	}

	@Override
	public void layoutParts() {
		this.getChildren().clear();
		int size = this.nodesProperty.size();
		if (size == 0 || this.getPrefWidth() <= 0 || this.getPrefHeight() <= 0) {
			return;
		}
		double width = this.getPrefWidth();
		double height = this.getPrefHeight();
		int rowNums = 1;
		if (size <= 0) {
			return;
		} else if (size == 1) {
		} else if (size <= 4) {
			rowNums = 2;
		} else {
			rowNums = 3;
		}
		for (int i = 0; i < this.nodesProperty.size() && i < 9; i++) {
			UIImage image = this.createImage(this.nodesProperty.get(i));
			this.initImage(image, i % rowNums, i / rowNums, width / rowNums, height / rowNums);
		}
		super.layoutChildren();
	}

	private void initImage(UIImage image, int col, int row, double width, double height) {
		this.getChildren().add(image);
		image.setPrefSize(width, height);
		GridPane.setConstraints(image, col, row);
		GridPane.setHalignment(image, HPos.CENTER);
		GridPane.setValignment(image, VPos.CENTER);
	}

	private UIImage createImage(Object o) {
		if (o == null) {
			throw new NoSupportException();
		}

		if (o instanceof String) {
			return UIImage.Image((String) o);
		}
		if (o instanceof Image) {
			return UIImage.Image((Image) o);
		}
		if (o instanceof InputStream) {
			return UIImage.Image((InputStream) o);
		}
		if (o instanceof ImageView) {
			return UIImage.Image((ImageView) o);
		}
		throw new NoSupportException();
	}

	@Override
	public void setupValueChangedListeners() {
		this.nodesProperty().addListener((ob, o, n) -> this.layoutParts());
	}

	public ListProperty<Object> nodesProperty() {
		return nodesProperty;
	}

}